package cn.edu.tju.wallet.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.wallet.domain.OverdraftRule;
import cn.edu.tju.wallet.dto.OverdraftRuleDTO;
import cn.edu.tju.wallet.service.OverdraftRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/rule/overdraft")
public class OverdraftRuleController {

    @Autowired
    private OverdraftRuleService overdraftRuleService;

    /**
     * 创建规则
     */
    @PostMapping("/create")
    public HttpResult<OverdraftRule> create(@RequestBody OverdraftRuleDTO dto) {
        try {
            OverdraftRule rule = overdraftRuleService.createOverdraftRule(dto);
            return HttpResult.success(rule);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }

    /**
     * 更新规则
     */
    @PutMapping("/update/{id}")
    public HttpResult<OverdraftRule> update(@PathVariable Long id, @RequestBody OverdraftRuleDTO dto) {
        try {
            OverdraftRule rule = overdraftRuleService.updateOverdraftRule(id, dto);
            return HttpResult.success(rule);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }

    /**
     * 删除规则
     */
    @DeleteMapping("/delete/{id}")
    public HttpResult<Void> delete(@PathVariable Long id) {
        try {
            overdraftRuleService.deleteOverdraftRule(id);
            return HttpResult.success(null);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }

    /**
     * 查询所有规则
     */
    @GetMapping("/list")
    public HttpResult<List<OverdraftRule>> list() {
        try {
            List<OverdraftRule> rules = overdraftRuleService.getAllRules();
            return HttpResult.success(rules);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }
}